package com.ddsso.auth.web.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import sun.misc.BASE64Decoder;

import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * @author zdd
 * @package com.ddsso.auth.web.util
 * @Time Created by zdd on 2016/11/15.
 * @description  认证加密模块:1.主要对存储的cookie中的SHARE_SESSIONID、token以及ihome-token（header）中的变量进行加密
 */
public class AuthDesCoderUtil {
    private static final  String AUTHO_KEY="TOKEN-I2P_COM-IHOME_TOKEN-SHARE_SESSIONID";

    static Logger logger= Logger.getLogger(AuthDesCoderUtil.class);

    /**
     * @description 对存在在前段以及传输在前端的共享session进行加密，注意在redis中存储的为明文
     * @param tokenOrSessionId
     * @return
     */
    public static String desEncryptTokenOrSessionId(final String tokenOrSessionId){
        try{
            if(StringUtils.isNotBlank(tokenOrSessionId)){
                //加密之前应该对字符串进行解编码

                final String token= getBASE64((DESCoderUtils.desEncrypt(tokenOrSessionId, DESCoderUtils.getKeyLength8(AUTHO_KEY)))); //加密后转码
                logger.info("加密后的字符串："+token);
                return token;
            }
            return "";
        }catch (Exception e){
            return "error";
        }
    }

    /**
     * @description 对接收到的共享session进行解密
     * @param tokenOrSessionIdEnc
     * @return
     */
    public static String desDecryptTokenOrSessionId(final String tokenOrSessionIdEnc){
        try{
            if(StringUtils.isNotBlank(tokenOrSessionIdEnc)){//解密前解码
                logger.info("解编码后64的字符串："+getFromBASE64(tokenOrSessionIdEnc));
                final String token=DESCoderUtils.desDecrypt(getFromBASE64(tokenOrSessionIdEnc), DESCoderUtils.getKeyLength8(AUTHO_KEY));
                logger.info("解密后的字符串："+token);
                return token;
            }
            return "";
        }catch (Exception e){
            return e.getMessage();
        }
    }


    public static void main(String [] args){
        String zz=desEncryptTokenOrSessionId("hhhhjkjksfhdkj");
        System.out.println("tt:"+zz);
        System.out.println("tt:"+desDecryptTokenOrSessionId(zz));
    }

    //进行base64位编码
    public static String getBASE64(String s) {
        if (s == null) return null;
        return (new sun.misc.BASE64Encoder()).encode( s.getBytes() );
    }

    // 将 BASE64 编码的字符串 s 进行解码
    public static String getFromBASE64(String s) {
        if (s == null) return null;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] b = decoder.decodeBuffer(s);
            return new String(b);
        } catch (Exception e) {
            return null;
        }
    }

}
